<template>
  <div id="app">

    <components :is="currentComponent"></components>

  </div>
</template>

<script>
import Login from "@/views/Login"
import Home from "@/views/Home"
import axios from "@/tools/axios";

export default {
  components: {
    Login, Home
  },
  data() {
    return {}
  },
  computed: {
    //是否登录
    isLogin() {
      return this.$store.getters.getIsLogin;
    },
    currentComponent() {
      return this.isLogin ? "Home" : "Login";
    }
  },
  created() {
    /**
     * 监听刷新事件,如果 F5 刷新了,就将数据写入到 sessionStorage
     */
    window.addEventListener('unload', () => {
      window.sessionStorage.setItem("vuex", JSON.stringify(this.$store.state))
    })

    /**
     * 从 sessionStorage 获取 vuex,如果值不为 null,对应的将值写入到对应的 state 中去
     */
    let data = window.sessionStorage.getItem("vuex");
    if (data != null) {
      let obj = JSON.parse(data);

      this.$store.dispatch('asyncSetIsLogin', obj.isLogin)
      this.$store.dispatch('asyncSetUserId', obj.userId)
      this.$store.dispatch('asyncSetToken', obj.token)
      this.$store.dispatch('asyncSetUserInfo', obj.userInfo)

      this.$store.dispatch('asyncSetOpenNames',obj.menu.openNames)
      this.$store.dispatch('asyncSetActiveName',obj.menu.activeName)
    }
  },
  mounted() {
    // console.log("app.vue");
    // console.log(this.$store.state);

    /**
     * 加载,只要 localStorage 中有数据就认为登录
     * @type {string}
     */
    let isLogin = window.localStorage.getItem("isLogin");
    if (isLogin) {
      //放入到vuex中
      let userId = window.localStorage.getItem("userId");
      let token = window.localStorage.getItem("token");
      let userStringify = window.localStorage.getItem("userStringify");
      let userInfo = JSON.parse(userStringify);
      this.$store.commit('setIsLogin', isLogin)
      this.$store.commit('setUserId', userId)
      this.$store.commit('setToken', token)
      this.$store.commit('setUserInfo', userInfo)
    }
  }
}
</script>

<style lang="less">
//全局样式
* {
  margin: 0px;
  padding: 0px;
}

// 文字上下左右居中
.tvc {
  text-align: center;
  vertical-align: middle;
}

//调试 bgc
.bgc {
  background-color: #ee7f95 !important;
}
</style>
